package com.limin.commanser.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.limin.commanser.controller.form.SearchLeaveByIdForm;
import com.limin.commanser.dto.*;
import com.limin.commanser.entity.Activity;
import com.limin.commanser.entity.Leave;
import com.limin.commanser.entity.PageUtils;
import com.limin.commanser.entity.User;
import com.limin.commanser.result.Result;
import com.limin.commanser.result.ResultGenerator;
import com.limin.commanser.service.ActivityService;
import com.limin.commanser.service.LeaveService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import cn.hutool.json.JSONUtil;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class LeaveController {
    private final LeaveService leaveService;

    @Autowired
    LeaveController(LeaveService leaveService) {
        this.leaveService = leaveService;
    }

    /*
     * 分页查询所有请假列表
     * @param pageNum
     * @param pageSize
     * @param order
     * @param activityId
     * @return Result
     */
    @GetMapping("/leaves")
    public Result findAllByPaging(  @RequestParam("pageNum") Integer pageNum,
                                    @RequestParam("pageSize") Integer pageSize,
                                    @RequestParam(value = "order", required = false, defaultValue = "DESC") String order,
                                    @RequestParam(value = "communityId", required = true) Integer communityId,
                                    @RequestParam(value = "leaveStatus", required = false) Integer leaveStatus)
    {
        PageHelper.startPage(pageNum, pageSize);
        Map<Object, Object> params = new HashMap<>();
//        params.put("leaveStuId", leaveStuId);
        params.put("order", order);
        params.put("communityId", communityId);
        params.put("leaveStatus", leaveStatus);
        List<LeaveDto> leaveDtos = leaveService.findAllByPaging(params);
        return ResultGenerator.genOkResult(leaveDtos);
    }


    /*
     * 分页查询自己的请假列表
     */
    @PostMapping("/leaves/searchLeaveById")
    @SaCheckLogin
    public Result searchLeaveById(@Valid @RequestBody SearchLeaveByIdForm form) {
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        if (!(StpUtil.hasPermission("LEAVE:SELECT") || StpUtil.hasPermission("ROOT"))) {
            param.put("userId", StpUtil.getLoginIdAsInt());
        }
        HashMap map = leaveService.searchLeaveById(param);
        return ResultGenerator.genOkResult(param);
    }


    /*
     * 查询总记录条数
     * @return Result
     */
    @GetMapping("/leaves/total")
    public Result findTotal() {
        return ResultGenerator.genOkResult(leaveService.findTotal());
    }


    /*
     *管理员根据ID删除信息
     * @param activityId
     * @return Result
     */
    @DeleteMapping("/leaves/{leaveId}")
    public Result removeById(@PathVariable Integer leaveId) {
        leaveService.removeById(leaveId);
        return ResultGenerator.genOkResult("ok");
    }

    /*
     * 修改请假信息
     * @param activity
     * @param userType
     * @param communityId
     * @return Result
     */
    @PutMapping("/leaves/{userType}/{communityId}")
    public Result editLeave(@RequestBody Leave leave,
                            @PathVariable("userType") Integer userType,
                            @PathVariable("communityId") Integer communityId) {
        User user = new User();
        user.setUserCommunityId(communityId);
        user.setUserType(userType);
        leaveService.modify(leave, user);
        return ResultGenerator.genOkResult("ok");
    }

    /*
     * 管理员审核请假
     * @param activity
     * @return Result
     */
    @PutMapping("/leaves/approval")
    public Result approvalLeave(@RequestBody Leave leave) {
        leaveService.approvalLeave(leave);
        return ResultGenerator.genOkResult("ok");
    }

    /*
     * 根据用户查询请假信息
     * @param userId
     * @param userType
     * @param activityType
     * @return Result
     */
    @GetMapping("/leaves/{userId}/{userType}/{leaveType}/{userCommunityId}")
    public Result findLeavesByUser(@PathVariable("userId") String userId,
                                   @PathVariable("userType") Integer userType,
                                   @PathVariable("leaveType") Integer leaveType,
                                   @PathVariable("userCommunityId") Integer userCommunityId) {
        User user = new User();
        user.setUserType(userType);
        user.setUserId(userId);
        user.setUserCommunityId(userCommunityId);
        Map<String, List<LeaveDto>> data = leaveService.findByUser(user, leaveType);
        return ResultGenerator.genOkResult(data);
    }

    /*
     * 荍荍：用户申请请假
     * @param [JoinLeaveDto]
     * @return com.limin.commanser.result.Result
     */
    @PostMapping("/leaves/join")
    public Result joinLeave(@RequestBody JoinLeaveDto joinLeaveDto) {
        //先检查时间约束，验证结束时间是不是早于开始时间
        String date1 = joinLeaveDto.getLeaveStartTime().toString();
        String date2 = joinLeaveDto.getLeaveEndTime().toString();
        DateTime date_1 = DateUtil.parse(date1);
        DateTime date_2 = DateUtil.parse(date2);
        if (date_1.isAfterOrEquals(date_2)) {
            System.out.println("请假时间不能晚于等于结束时间");
            //返回错误提示
            return ResultGenerator.genFailureResult("请假时间不能晚于等于结束时间");
        } else {
            //判断当前请假是否跟其他请假有交集
            HashMap param = new HashMap() {{
                put("userId", joinLeaveDto.getLeaveStuId());
                put("start", joinLeaveDto.getLeaveStartTime());
                put("end", joinLeaveDto.getLeaveEndTime());
            }};
            if (leaveService.searchContradiction(param)) {
                return ResultGenerator.genFailureResult("当前请假申请与已有请假申请日期上有交集覆盖");
            }
            try {
                //加8小时

                leaveService.joinLeave(joinLeaveDto);
            } catch (Exception e) {
                System.out.println("请假失败" + joinLeaveDto.toString() + e);
                return ResultGenerator.genFailureResult("请假申请出错！");
            }
            return ResultGenerator.genOkResult("ok");
        }
    }

    /*
     * 荍荍：学生分页查询自己的请假记录
     */
    @GetMapping("leaves/searchLeaveByPage")
    public Result searchLeaveByPage(@RequestParam("page") Integer pageNum,
                                    @RequestParam("length") Integer pageSize,
                                    @RequestParam("userId") String userId
                                    ,@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "date", required = false) Date date,
                                    @RequestParam(value = "status", required = false) Integer status,
                                    @RequestParam(value = "type", required = false) Integer type
    ) {
        int page = pageNum;
        int length = pageSize;
        int start = (page - 1) * length;
        HashMap param = new HashMap();
        param.put("start", start);
        param.put("length", length);
        param.put("myId", userId);
        if (date != null) {
            param.put("date", date);
        }
        if (status != null) {
            param.put("status", status);
        }
        if (type != null) {
            param.put("type", type);
        }
        PageUtils pageUtils = leaveService.searchLeaveByPage(param);
        return ResultGenerator.genOkResult(pageUtils);
    }

    /*
     * 荍荍：学生删除自己的请假记录
     */
    @PostMapping("leaves/deleteLeaveById/{deleteId}")
    public Result deleteLeaveById(@PathVariable("deleteId") Integer deleteId) {
        int rows = leaveService.deleteLeaveById(deleteId);
        return ResultGenerator.genOkResult(rows);
    }

    /*
     * 荍荍：修改用户信息
     * @param dto
     * @return Result
     */
    @PostMapping("leaves/updateLeaveInfo")
    public Result update(@RequestBody UpdateLeaveDto dto) {
        leaveService.update(dto);
        return ResultGenerator.genOkResult();
    }


}
